// Main.cs
//
//  Copyright (C) 2008 Jacek Trubłajewicz
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//

using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using System.Text;
using Mono.Unix;
using NLog;
using NLog.Config;
using NLog.Targets;
using NLog.Layouts;


namespace wxGadu
{
	public class MainApp
	{
#if RELEASE
		static bool createdNew;
		static Mutex singleInstance = new Mutex(true, "wxGadu instance", out createdNew);
#endif
		
		public static void Main()
		{
#if RELEASE	
			//if (singleInstance.WaitOne(TimeSpan.Zero, true))
			if (createdNew)
		    {
				Catalog.Init("i18n","./locale");
				wxGaduApp app = new wxGaduApp();
				app.Run();
			}
			else
			{
				System.Console.WriteLine(Catalog.GetString("wxGadu is already running, exiting..."));
			}
#endif
			
#if DEBUG
			Catalog.Init("i18n","./locale");
			wxGaduApp app = new wxGaduApp();
			app.Run();
#endif
			
		}
	}

	public class wxGaduApp : wx.App
	{
//#if LOG
//		private Logger logger = LogManager.GetCurrentClassLogger();
//#endif
		private GaduTaskBarIcon ticon;
		
		public override bool OnInit()
		{	
			InitializeSimpleLogging();
			
			// TODO: do better folders checking upon start
			#region home dir check
			string homeDir;
			StringBuilder sb = new StringBuilder();
			sb.Append(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
			sb.Append(Path.DirectorySeparatorChar); 
			sb.Append(".");
			sb.Append(AppConfig.APP_NAME);
			homeDir = sb.ToString();
			
			if (!Directory.Exists(homeDir))
			{
				try
				{
					Directory.CreateDirectory(homeDir);
				}
				catch (Exception e)
				{
					wx.MessageDialog md3 = new wx.MessageDialog(null, String.Format(
					                                                                Catalog.GetString("Unable to create user home directory {0}. Cannot procced without it. Check your permissions and restart the application. \n\n{1}"),
				                                                               homeDir, e.Message),
				                                           Catalog.GetString("Error"),
			                                           wx.MessageDialog.wxOK|wx.MessageDialog.wxICON_EXCLAMATION);
					md3.ShowModal();
					Environment.Exit(0);
				}
			}
			#endregion
			
			// initialize lists of images loaded from embeded resources file
			ImageManager imageManager = new ImageManager();
			
			LoginDialog loginDialog = new LoginDialog(null, -1, "wxGadu", new Point(0, 0), wx.Window.wxDefaultSize,
			                                                  wx.Dialog.wxDEFAULT_DIALOG_STYLE|wx.Dialog.wxRESIZE_BORDER, imageManager);
			
			
			if (loginDialog.ShowModal() == wx.Dialog.wxID_CANCEL)
				Environment.Exit(0);
			

			AppConfig appConfig = new AppConfig(loginDialog.ProfileName, loginDialog.Password);
			InitializeProperLogging(appConfig);
			MainFrame mainWindow = new MainFrame(null, -1, "wxGadu", appConfig.UserConf.MainWindowPosition, wx.Window.wxDefaultSize,
			                                     wx.Frame.wxDEFAULT_FRAME_STYLE|wx.Frame.wxDEFAULT_FRAME,
			                                     appConfig, imageManager);
			loginDialog.Dispose();
			mainWindow.Show(true);	

			return true;
		}
		
		/// <summary>
		/// Initializes logging manager
		/// </summary>
		/// <remarks>
		/// This logger settings are used only before creating <c>AppConfig</c>
		/// </remarks>
		private void InitializeSimpleLogging()
		{
			LoggingConfiguration configuration = new LoggingConfiguration();
			
			ConsoleTarget console = new ConsoleTarget();
		
			
			configuration.AddTarget(AppConfig.CONSOLE_LOG_TARGET_NAME, console);
		
			
			console.Layout = "${level} | ${message} ${newline}@${stacktrace}";
			
			
			LoggingRule consoleRule = new LoggingRule("*", NLog.LogLevel.Trace, console); 
			configuration.LoggingRules.Add(consoleRule); 
						
			LogManager.Configuration = configuration;
		}
		
		/// <summary>
		/// Initializes logging manager
		/// </summary>
		/// <param name="appCfg">
		/// A <see cref="AppConfig"/>
		/// </param>
		/// <remarks>
		/// This method does proper logger initialization based on <c>AppConfig</c>
		/// </remarks>
		private void InitializeProperLogging(AppConfig appCfg)
		{
			LogManager.Configuration = null;
			LoggingConfiguration configuration = new LoggingConfiguration();
			
			ConsoleTarget console = new ConsoleTarget();
			FileTarget file = new FileTarget();
			
			configuration.AddTarget(AppConfig.CONSOLE_LOG_TARGET_NAME, console);
			configuration.AddTarget(AppConfig.FILE_LOG_TARGET_NAME, file);
			
			console.Layout = "${level} | ${message} ${newline}@${stacktrace}";
			file.Layout = "${level} | ${longdate} | ${message} ${newline}@${stacktrace}";
			file.FileName = appCfg.LogFile;
			
			LoggingRule consoleRule = new LoggingRule("*", NLog.LogLevel.FromString(appCfg.UserConf.ConsoleLoggingLevel.ToString()), console); 
			configuration.LoggingRules.Add(consoleRule); 
			LoggingRule fileRule = new LoggingRule("*", NLog.LogLevel.FromString(appCfg.UserConf.FileLoggingLevel.ToString()), file); 
			configuration.LoggingRules.Add(fileRule); 
			
			LogManager.Configuration = configuration;
		}


	}
}
